package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZJ
 * 监听spu表的变化
 */
@CanalEventListener
public class SpuListener {

  @Autowired
  private RabbitTemplate rabbitTemplate;

  /**
   * spu 表更新
   *
   * @param eventType
   * @param rowData
   */
  @ListenPoint(schema = "changgou_goods", table = {"tb_spu"}, eventType = CanalEntry.EventType.UPDATE)
  public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
    System.err.println("tb_spu表数据发生变化");

    //修改前数据
    Map oldMap = new HashMap<>();
    for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
      oldMap.put(column.getName(), column.getValue());
    }

    //修改后数据
    Map newMap = new HashMap<>();
    for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
      newMap.put(column.getName(), column.getValue());
    }

    /**
     * is_marketable  由改变签的0改为改变后的 1表示是最新上架的商品
     */
    if ("0".equals(oldMap.get("is_marketable")) && "1".equals(newMap.get("is_marketable"))) {
      //监听到有消息发生变化就发送到mq
      rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", newMap.get("id")); //发送到mq商品上架交换器上
    }

    //获取最新下架的商品,原数据为1,现在数据为0,表示下架的
    if ("1".equals(oldMap.get("is_marketable")) && "0".equals(newMap.get("is_marketable"))) {
      //监听到有消息发生变化就发送到mq
      rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE, "", newMap.get("id")); //发送到mq商品上架交换器上
    }


    /**
     * 获取最新被审核通过的商品发送到mq,生成静态页面
     *status从0变成1 ,就是最新被审核的
     */
    if ("0".equals(oldData.get("status")) && "1".equals(newData.get("status"))) {
      //发送商品spuId,到mq交换机PAGE_CREATE_EXCHANGE,路由key给""
      rabbitTemplate.convertAndSend(RabbitMQConfig.PAGE_CREATE_QUEUE, "", newData.get("id"));
    }
  }
